﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using CoolCode.Entities;
using CoolCode.Services;
using CoolCode.Web;
using CoolCode.Linq;

namespace CoolCode.Web.UI.Controls
{
    public partial class MenuInUsers : PartialView<List<RoleView>, string>
    {
        private IMenuService _MenuService;
        public IMenuService MenuService
        {
            get
            {
                if (_MenuService == null)
                {
                    _MenuService = ServiceFactory.Produce<IMenuService>();
                }
                return _MenuService;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            handleEvents();
        }

        protected void handleEvents()
        {
            lnkSave.Click += new EventHandler(lnkSave_Click);
            new string[] { "chkRead", "chkWrite", "chkDelete", "chkExport" }
                .ForEach(c => gvMaster.HandleSelectAll(c + "SelectAll", c));
        }

        public override void Show(string key)
        {
            base.Show(key);
            lblDspUser.Text = key;
            gvMaster.DataSource = this.MenuService.ListMenuInUser(key);
            gvMaster.DataBind();
            udpHeader.Update();
        }

        protected void lnkSave_Click(object sender, EventArgs e)
        {
            MembershipUser user = Membership.GetUser(lblDspUser.Text);
            if (user == null)
            {
                udpHeader.Alert("用户名不存在或者用户已经被删除！");
                return;
            }
            List<RoleView> list = new List<RoleView>();
            foreach (GridViewRow gvr in gvMaster.Rows)
            {
                RoleView entity = new RoleView
                {
                    MenuID = gvMaster.GetKey<int>(gvr.RowIndex),
                    BelongTo = lblDspUser.Text,
                    CanRead = gvr.IsSelected("chkRead"),
                    CanWrite = gvr.IsSelected("chkWrite"),
                    CanDelete = gvr.IsSelected("chkDelete"),
                    CanExport = gvr.IsSelected("chkExport"),
                };
                list.Add(entity);
            }
            this.MenuService.SaveMenuInUser(list, null);
            udpHeader.Alert("操作成功！");
            OnClosing();

            //BindData();
            //udpHeader.Update();
        }

        //private void BindData()
        //{
        //    string user = txtUser.Text;
        //    gvMaster.DataSource = this.MenuService.ListMenuInUser(user);
        //    gvMaster.DataBind();
        //}
    }
}